package com.info.zhiduoduo.weixin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.info.zhiduoduo.common.configs.UploadPathConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.formbean.BaseAuthInfo;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.system.CityCategoryDto;
import com.info.zhiduoduo.repository.dto.system.ProjectCategoryBriefDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.crm.CrmSystemDict;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.system.EnterpriseIndustry;
import com.info.zhiduoduo.repository.entity.system.SystemCfg;
import com.info.zhiduoduo.repository.entity.system.SystemTradeCategory;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.repository.mapper.system.CityInvoiceCategoryMapper;
import com.info.zhiduoduo.repository.mapper.system.EnterpriseIndustryMapper;
import com.info.zhiduoduo.repository.mapper.system.ProjectCategoryMapper;
import com.info.zhiduoduo.repository.mapper.system.TradeCategoryMapper;
import com.info.zhiduoduo.weixin.formbean.system.PhoneFormBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Transactional
@Service
public class SystemService extends BaseService {

	@Autowired
	CommonService commonService;
	@Resource
	CompanyMapper companyMapper;

	@Resource
	MakerMapper makerMapper;

	@Resource
	PartnerMapper partnerMapper;

	@Resource
	ProjectCategoryMapper projectCategoryMapper;
	@Resource
	TradeCategoryMapper tradeCategoryMapper;
	@Resource
	EnterpriseIndustryMapper industryMapper;

	@Resource
	CityInvoiceCategoryMapper cityInvoiceCategoryMapper;

	@Autowired
	UploadPathConfig uploadPathConfig;

	@Autowired
	HttpServletRequest request;

	public SmartResult getPhoneCode(BaseSimpleFormBean<PhoneFormBean> baseSimpleFormBean, String ipAddr) {
		SmartResult smartResult = new SmartResult();

		PhoneFormBean phoneFormBean = baseSimpleFormBean.getReqdata();

		if (null == phoneFormBean || StringUtil.isEmpty(phoneFormBean.getPhone())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String phone = phoneFormBean.getPhone();

		//1创客 2企业 3合伙人
		int identityType = baseSimpleFormBean.getIdtype();
		if (UserType.MAKER == identityType) {
			//查看企业是否已经注册
			Company company = companyMapper.checkCompanyExistByPhone(phone);
			if (null != company) {
				smartResult.setStateMsg(StatusMsg.StatusMsg_108);
				return smartResult;
			}
		} else if (UserType.COMPANY == identityType) {
			//查看个人是否已经注册
			Maker maker = makerMapper.checkUserExistByPhone(phone);
			if (null != maker) {
				smartResult.setStateMsg(StatusMsg.StatusMsg_109);
				return smartResult;
			}
		}

		return commonService.sendPhoneVerifyCode(request, phone);
	}

	public SmartResult getProjectCategory(BaseAuthInfo baseAuthInfo) {
		SmartResult smartResult = new SmartResult();

		List<ProjectCategoryBriefDto> projectCategoryBriefDtoList = projectCategoryMapper.queryPorjectCategory();

		smartResult.setList(projectCategoryBriefDtoList);
		return smartResult;
	}

	public SmartResult getTradeCategory(BaseAuthInfo baseAuthInfo) {
		SmartResult smartResult = new SmartResult();

		List<SystemTradeCategory> tradeCategoryList = tradeCategoryMapper.selectList(new EntityWrapper<SystemTradeCategory>());

		List<SystemTradeCategory> parentTradeCategoryList = new ArrayList<>();

		Map<Integer, List<SystemTradeCategory>> integerListMap = new HashMap<>();

		if (null != tradeCategoryList && tradeCategoryList.size() > 0) {
			for (SystemTradeCategory SystemTradeCategory : tradeCategoryList) {
				if (SystemTradeCategory.getParentid() == 0) {
					parentTradeCategoryList.add(SystemTradeCategory);
				} else {
					List<SystemTradeCategory> childTradeCategory = integerListMap.get(SystemTradeCategory.getParentid());
					if (null == childTradeCategory || childTradeCategory.size() == 0) {
						childTradeCategory = new ArrayList<>();
					}
					childTradeCategory.add(SystemTradeCategory);
					integerListMap.put(SystemTradeCategory.getParentid(), childTradeCategory);
				}
			}
		}

		for (SystemTradeCategory SystemTradeCategory : parentTradeCategoryList) {
			SystemTradeCategory.setChildTradeCategory(integerListMap.get(SystemTradeCategory.getTradecategoryid()));
		}

		smartResult.setList(parentTradeCategoryList);
		return smartResult;
	}

	public SmartResult<EnterpriseIndustry> getEnterpriseIndustryList() {
		return SmartResult.success(industryMapper.list(""));
	}

	public SmartResult<Map<Integer, List<CrmSystemDict>>> CrmSystemDictList(String typies) {
		Map<Integer, List<CrmSystemDict>> map = Stream.of(typies.split(","))
				.flatMap(type -> new CrmSystemDict().selectList(Condition.create().eq("dict_type", type)).stream())
				.collect(Collectors.groupingBy(CrmSystemDict::getDictType));
		return SmartResult.success(map);
	}



	/**
	 * 获取城市开票类目
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult queryAllCityCategoryList(BaseSimpleFormBean<Integer> baseSimpleFormBean) {

		Integer cityId = baseSimpleFormBean.getReqdata();
		// 获取 一级列表
		List<CityCategoryDto> categoryList = cityInvoiceCategoryMapper.selectCityCategoryList(cityId , null);
		// 获取 二级列表
		categoryList.forEach((categoryDto) -> {
			categoryDto.setInvoiceCategoryDtoList(  cityInvoiceCategoryMapper.selectCityCategoryByTwoList( categoryDto.getId() )   );
		}  );
		return smartResult( categoryList );
	}

	/**
	 * 查看系统限制交易的时间段
	 * @return
	 */
	public SmartResult queryRestraintTradeTime(){
		SystemCfg start = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_START);
		SystemCfg end = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_END);
		if(start != null && end != null){
			return smartResult(start.getCfgValue() + "-" + end.getCfgValue());
		}
		return emptyDataSmartResult();
	}

}
